package 二叉树.树左下角的值;

import java.util.LinkedList;
import java.util.Queue;
import java.util.regex.Pattern;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/2/15 17:16
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        TreeNode root  = new TreeNode(1,new TreeNode(2),new TreeNode(3));
        System.out.println(findBottomLeftValue(root));
    }

    public static int findBottomLeftValue(TreeNode root) {
        //DFS遍历求出深度
        int depth = maxDepth(root);
        //BFS遍历 在最底层找到的最左边的节点
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int level = 0;
        while (!queue.isEmpty()){
            if (level == depth-1){
                return queue.poll().val;
            }
            int size = queue.size();
            while (size > 0){
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null){
                    queue.offer(node.right);
                }
                size--;
            }
            level++;
        }
        return 0;
    }

    public static int maxDepth(TreeNode root){
        if(root == null){
            return 0;
        }else {
            int left = maxDepth(root.left);
            int right = maxDepth(root.right);
            return Math.max(left,right) + 1;
        }
    }

    public static int findBottomLeftValue2(TreeNode root){
        if (root == null){
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int ans = 0;
        while (!queue.isEmpty()){
            int size = queue.size();
            int target = 0;
            while (size > 0){
                TreeNode node = queue.poll();
                if (target == 0){
                    ans = node.val;
                }
                target = -1;
                if (node.left != null){
                    queue.offer(node.left);
                }
                if (node.right != null){
                    queue.offer(node.right);
                }
                size--;
            }
        }
        return ans;
    }
}
